<?xml version="1.0" encoding="utf-8" ?>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%--<%
    // String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
%>--%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户中心--layui后台管理模板 2.0</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <%--<base href="<%=basePath%>">--%>
</head>
<body>
    <div>
       <h1>欢迎来到WebSocket页面</h1>
    </div>

    <form id="sendFrom">
        发送消息: <input type="text" id="message" name="message">
        发给谁: <input type="text" name="sid" id="sid">
        <button id="send" type="button">发送</button>
    </form>
</body>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript">
    var socket;
    if(typeof(WebSocket) == "undefined") {
        alert("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        // socket = new WebSocket("ws://localhost:80/websocket/${cid}");
        socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            socket.send("这是来自客户端的消息" + location.href + "  " + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
        //离开页面时，关闭socket
        //jquery1.8中已经被废弃，3.0中已经移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }

    $('#send').click(function() {
        var url = '${basePath}checkcenter/socket/push/msg';
        var sid = $('#sid').val();
        if(sid) {
            url = url + '/' + sid;
        }
        $.getJSON(url,$('#sendFrom').serialize(),function(data){
            if (data.code === 200) {

            }
        })
    })
</script>
</html>